package com.usian.search.filter;

import com.usian.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Fay
 * @date 2022/7/21&16:41
 */
@Slf4j
@Order(1)
@WebFilter(filterName = "appTokenFilter", urlPatterns = "/api/*")
public class AppTokenFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        //获取userId
        String userId = request.getHeader("userId");
        //将userId放到线程中
        if (!StringUtils.isEmpty(userId) && !userId.equals("0")){
            UserThreadLocalUtils.setUserId(Integer.parseInt(userId));
        }
        //放行
        chain.doFilter(req,res);
    }
}
